import qs from 'qs'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

import axios from 'axios'

// 创建axios实例
export const service = axios.create({
  // baseURL: 'http://www.aidolphins.com:11000' + process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 30000,
  headers: []
})


// request拦截器  前端给后端的请求
service.interceptors.request.use(
  config => {
    if (parseInt(storage.get("loginType")) === 0){
      config.headers['tokens'] = "dabe69138599589384452ac32a0f43d6"
    }else{
      config.headers['tokens'] = storage.get("bmwToken") || "";
    }
    config.headers["Content-Type"] = "application/json;charset=utf-8"; // 配置请求头
    config.headers['env'] = process.env.NODE_ENV

    if (storage.get(ACCESS_TOKEN)) {
      config.headers['token'] = storage.get(ACCESS_TOKEN)
    }
    if (config.data === undefined) {
        // 写死了
        config.headers['YtAuth'] = jwt.encode({ "bmw": 1 }, "jwt")
    } else {
        // 过期时间
        config.data.exp = Math.floor(Date.now() / 1000) + 10;
        // 加密数据
        config.headers['YtAuth'] = jwt.encode(config.data, "jwt")
    }
    return config
  },
  error => {
    // 请求错误
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// respone拦截器  后端给前端的响应
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (response.status !== 200 || res.code !== 1) {
      return Promise.reject(res.showMsg)
    } else {
      return res
    }
  },
  error => {
    let message = ''
    if (error.response) {
      const {
        status,
        data
      } = error.response
      switch (status) {
        case 400:
          message = '400:错误的请求'
          break
        case 403:
          message = '403:服务器拒绝了对所请求资源的访问'
          break
        case 404:
          message = '404:网络请求不存在'
          break
        case 500:
          message = '500:服务器断开连接，请稍后再试'
          break
        case 502:
          message = '502:服务器没有响应，请稍后再试'
          break
        case 503:
          message = '503:因维护而停机，无法处理请求'
          break
        default:
          message = `Error:${data.showMsg}`
      }
    } else {
      if (error.message.includes('timeout')) {
        message = `Error:请求超时! 请检查网络是否正常`
      } else {
        message = `Error:请求失败，请检查网络是否已连接`
      }
    }
    return Promise.reject({
      message
    })
  }
)


export function post(url, data, headers) {
  return service({
    method: 'post',
    url: url,
    data: data,
    headers: headers || {}
  })
}

export function get(url, params, headers) {
  return service({
    method: 'get',
    url,
    params: params,
    headers: headers || {}
  })
}

export function formData(url, data) {
  return service({
    method: 'POST',
    url,
    data,
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}